package com.whisperly.echotalk.account;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.whisperly.echotalk.bllmodel.CommonResponse;
import com.whisperly.echotalk.bllmodel.FindPasswordDto;
import com.whisperly.echotalk.bllmodel.FindPasswordResponse;
import com.whisperly.echotalk.bllmodel.ResultBody;
import com.whisperly.echotalk.bllmodel.UpdatePasswordDto;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.netWorkUtils.BlinkCallback;
import com.whisperly.echotalk.starryb.netWorkUtils.NetworkUtils;
import com.whisperly.echotalk.starryb.schemas.Login;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.GlobalData;
import com.whisperly.echotalk.starryb.utils.SendGmail;

import java.util.Locale;

public class FindPassword extends AppCompatActivity {
    private Button validate,btnSendCode;
    private EditText etUserName, etEmail,verification;
    private Toast current;
    private String email,userName,userInputCode;
    private CountDownTimer countDownTimer;
    private View loadingView;
    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_password);
        AppsManager.addActivity(this);
        etUserName = findViewById(R.id.user_name);
        etEmail = findViewById(R.id.email);
        validate = findViewById(R.id.confirm);
        btnSendCode = findViewById(R.id.btn_send_code);
        verification = findViewById(R.id.verification_code);
        loadingView = getLayoutInflater().inflate(R.layout.layout_loading, null);

        validate.setOnClickListener(v -> validateInfo());
        btnSendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = etEmail.getText().toString().trim();
                if (isValidEmail(email)){
                    startCountDown();
                    // 调用发送验证码的方法
                    SendGmail.generateCode(email);
                    SendGmail.sendEmail(email,v, FindPassword.this);
                }else {
                    etEmail.setError(getString(R.string.invalid_email_address));
                }
            }
        });
    }
    private boolean isValidEmail(String email) {
        return Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void startCountDown() {
        btnSendCode.setEnabled(false); // 禁用按钮防止重复点击
        countDownTimer = new CountDownTimer(60000, 1000) {
            public void onTick(long millisUntilFinished) {
                btnSendCode.setText(getString(R.string.resend_code_in, millisUntilFinished / 1000));
            }

            public void onFinish() {
                btnSendCode.setText(R.string.send_code);
                btnSendCode.setEnabled(true); // 重新启用按钮
            }
        }.start();
    }

    private void validateInfo() {
        showLoading();
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            userName = etUserName.getText().toString().trim();
            email = etEmail.getText().toString().trim();
            userInputCode = ((EditText) findViewById(R.id.verification_code)).getText().toString().trim();

            // 检查必要字段
            if (!validateRequiredFields()) {
                return;
            }

            // 验证验证码
            if (!validateVerificationCode()) {
                return;
            }

            // 所有验证通过，执行找回密码流程
            submitFindPasswordRequest();

        }, 1000);
    }

    /**
     * 验证必填字段
     * @return 验证是否通过
     */
    private boolean validateRequiredFields() {
        // 验证码不能为空
        if (userInputCode.isEmpty()) {
            showToast(R.string.Please_enter_the_verification_code);
            verification.setError(getString(R.string.Please_enter_the_verification_code));
            hideLoading();
            return false;
        }

        // 可以在这里添加其他字段验证，如用户名、邮箱格式等

        return true;
    }

    /**
     * 验证验证码
     * @return 验证是否通过
     */
    private boolean validateVerificationCode() {
        // 1. 检查验证码是否过期
        if (SendGmail.isCodeValid(email)) {
            showToast(R.string.Verification_code_has_expired);
            verification.setError(getString(R.string.Verification_code_has_expired));
            hideLoading();
            return false;
        }

        // 2. 获取存储的验证码
        String verificationCode = SendGmail.getVerificationCode(email);
        if (verificationCode == null || verificationCode.isEmpty()) {
            showToast(R.string.Verification_code_has_expired);
            verification.setError(getString(R.string.Verification_code_has_expired));
            hideLoading();
            return false;
        }

        // 3. 验证邮箱和验证码
        String[] split = verificationCode.split(":");

        // 验证邮箱匹配
        if (!email.equals(split[0])) {
            showToast(R.string.Email_is_incorrect);
            verification.setError(getString(R.string.Email_is_incorrect));
            hideLoading();
            return false;
        }

        // 验证验证码匹配
        if (!userInputCode.equals(split[1])) {
            showToast(R.string.Verification_code_is_incorrect);
            verification.setError(getString(R.string.Verification_code_is_incorrect));
            hideLoading();
            return false;
        }

        return true;
    }

    /**
     * 提交找回密码请求
     */
    private void submitFindPasswordRequest() {
        FindPasswordDto findPasswordDto = new FindPasswordDto();
        findPasswordDto.setName(userName);
        findPasswordDto.setEmail(email);

        NetworkUtils.findPassword(findPasswordDto, new BlinkCallback() {
            @Override
            public void onSuccess(ResultBody<?> response) {
                if (response.getCode() == 200) {
                    FindPasswordResponse data = (FindPasswordResponse) response.getData();
                    if (data.getSuccess()) {
                        showResetPasswordDialog();
                        GlobalData.setUser(data.getUserWithChat().getObjectId(), data.getUserWithChat());
                    } else {
                        showToast(R.string.double_check);
                    }
                } else {
                    showToast(R.string.Network_error);
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                showToast(R.string.Network_error);
            }
        });
        hideLoading();
    }

    /**
     * 显示Toast消息
     */
    private void showToast(int stringResId) {
        if (current != null) {
            current.cancel();
        }
        current = Toast.makeText(this, stringResId, Toast.LENGTH_SHORT);
        current.show();
    }


    private void showResetPasswordDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.reset_password, null);
        final EditText etNewPassword = dialogView.findViewById(R.id.et_new_password);
        final EditText etConPassword = dialogView.findViewById(R.id.et_confirm_password);

        builder.setView(dialogView)
                .setTitle(R.string.Reset_your_password)
                .setCancelable(false)
                .setPositiveButton(R.string.confirm, null)
                .setNegativeButton(R.string.cancel, (dialog, which) -> dialog.cancel());

        AlertDialog dialog = builder.create();
        dialog.setOnShowListener(dialogInterface -> {
            Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(view -> {
                String newPassword = etNewPassword.getText().toString().trim();
                String conPassword = etConPassword.getText().toString().trim();

                if (newPassword.isEmpty()){
                    if (current!=null){
                        current.cancel();
                    }
                    current = Toast.makeText(this, R.string.Please_d_leave_it_blank, Toast.LENGTH_SHORT);
                    current.show();
                    etNewPassword.setError("");
                }else if (conPassword.isEmpty()){
                    if (current!=null){
                        current.cancel();
                    }
                    current = Toast.makeText(this, R.string.Please_d_leave_it_blank, Toast.LENGTH_SHORT);
                    current.show();
                    etConPassword.setError("");
                }else if (!newPassword.equals(conPassword)){
                    if (current!=null){
                        current.cancel();
                    }
                    current = Toast.makeText(this, R.string.The_password_is_inconsisten_twice, Toast.LENGTH_SHORT);
                    current.show();
                    etConPassword.setError(getString(R.string.The_password_is_inconsisten_twice));
                }else {

                    resetUserPassword(newPassword);
                    dialog.dismiss();
                }
            });
        });
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
    private void resetUserPassword(String newPassword) {
        UserWithChat user = GlobalData.getUser();
        UpdatePasswordDto updatePasswordDto = new UpdatePasswordDto();
        updatePasswordDto.setOldPassword(user.getPassword());
        updatePasswordDto.setPassword(newPassword);
        updatePasswordDto.setObjectId(user.getObjectId());
        NetworkUtils.changePassword(updatePasswordDto, new BlinkCallback() {
            @Override
            public void onSuccess(ResultBody<?> response) {
                if (response.getCode() == 200){
                    CommonResponse data = (CommonResponse)response.getData();
                    if (data.getSuccess()){
                        if (current!=null){
                            current.cancel();
                        }
                        current = Toast.makeText(FindPassword.this, R.string.New_password_set_successfully, Toast.LENGTH_SHORT);
                        current.show();
                        Intent intent = new Intent(FindPassword.this, Login.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                        finish();
                        return;
                    }
                }
                current = Toast.makeText(FindPassword.this, R.string.Please_try_again_later, Toast.LENGTH_SHORT);
                current.show();
            }

            @Override
            public void onFailure(Throwable throwable) {
                current = Toast.makeText(FindPassword.this, R.string.Network_error, Toast.LENGTH_SHORT);
                current.show();
            }
        });
    }

    private void showLoading() {
        if (loadingView.getParent() == null) {
            ((ViewGroup) findViewById(android.R.id.content)).addView(loadingView);
            Log.d("LoginActivity", "Loading view added");
        }
    }

    private void hideLoading() {
        ((ViewGroup) findViewById(android.R.id.content)).removeView(loadingView);
    }
}
